package com.hexinfo.dmpro.sparing.async;

import cn.hutool.core.io.file.FileAppender;
import com.hexinfo.dmpro.sparing.dto.DistCPDTO;
import com.hexinfo.dmpro.sparing.dto.StateDataDTO;
import com.hexinfo.dmpro.sparing.dto.TableDistCPDTO;
import com.hexinfo.dmpro.sparing.model.HdfsHeatBackup;
import com.hexinfo.dmpro.sparing.service.DistCPService;
import com.hexinfo.dmpro.sparing.service.FutureService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

@Component
@AllArgsConstructor
@Slf4j
public class AsyncTableDistcp {

    @Autowired
    private DistCPService distCPService;
    @Autowired
    private FutureService futureService;

    /**
     * 按源--无时间分区字段--全量热备
     */
    @Async
    public Future<Boolean> allQuantity(TableDistCPDTO tableDistCPDTO, FileAppender tableLog, FileAppender heatlog , int sizes) {
        List<Future<Boolean>> futures = new ArrayList<>();
        for (HdfsHeatBackup hdfsHeatBackup : tableDistCPDTO.getHdfsHeatBackups()){
            DistCPDTO distCPDTO = new DistCPDTO(
                    tableDistCPDTO.getSourceDataName(),
                    hdfsHeatBackup,
                    tableDistCPDTO.getHdfsHeatBackups().size(),
                    heatlog,
                    tableLog);
            //第一步：热备到备份---备份到目标
            futures.add(distCPService.execShell(distCPDTO, sizes, tableDistCPDTO.getTableId()));
        }
        //判断表全部完成
        StateDataDTO stateDataDTO = futureService.futureStatusList(futures, heatlog, "数据同步");
        distCPService.souTableIsFinish(tableDistCPDTO.getSourceDataName(),tableDistCPDTO.getTableId(),
                tableDistCPDTO.getSouDbTbName(),heatlog,tableLog,stateDataDTO.isState());
        return new AsyncResult<>(stateDataDTO.isState());
    }
}
